import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/components/Login'
import home from '@/components/Home'
import welcome from '@/components/Welcome'
import users from '@/components/user/Users'

Vue.use(VueRouter)


const router =  new VueRouter({
  routes: [
    {
      path: '/',
      // 当路径为/时自动跳转到/login
      redirect:'/login'
    },
    {
      path:'/login',
      component:login
    },
    {
      path:'/home',
      component:home,
      redirect:'/welcome',
      children:[
        {
          path:'/welcome',
          component:welcome
        },
        {
          path:'/users',
          component:users,
        }
      ]
    }
  ]
})

// 挂载路由导航守卫
router.beforeEach((to,from,next)=>{
  // to 是将要访问的路径
  // from 代表从那个路径跳转而来
  // next 函数，放行函数next()  next('/路径')

  // 如果访问登录页，直接放行
  if(to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  // 若无token则直接跳回登录页
  if(!tokenStr) return next('/login')
  // 有token放行
  next()
})

export default router


